$(function () {
    vm.detail();
    layui.form.on('select(type)', function (data) {
        vm.applyForDTO.returnType = data.value;
    })

    //退换车时间
    layui.laydate.render({
        elem: '#date',
        type: 'date',
        trigger: 'click',
        // min:minTime,
        done: function (value) {
            vm.applyForDTO.timeApply = value;
        }
    });

    layui.form.render();

    uploadAttachment();
    //保存
    layui.form.on('submit(submitEditData)', function () {
        vm.saveOrUpdate();
        return false;
    });


});

var viewer;
var vm = new Vue({
    el: '#rrapp',
    data: {
        applyForDTO: {},
        title: null,
        dateLabel:null,
        settleAmount: null,
        amount: {},
        settleType: null,
        deliveryFileLst: [],
        deliveryFileLstId: 'deliveryFileLstId_0',
        //仓库数据源
        warehouseData:{},
        preData:{},
        backAmount:[],
        illLegalAmount:[],
        insuranceAmount:[],
        decutionAmount:[],
        bankInfo:[],
        notice:[],
        serviceProperty:{}
    },
    computed: {},
    methods: {
        initOrderData:function(order){
                vm.preData.carNo=order.orderCar.carNo;
                vm.preData.code=order.orderCar.code;
                vm.preData.customerName=order.customerName;
                vm.preData.rentTypeStr=order.orderCar.rentTypeStr;
                vm.preData.rentType=order.orderCar.rentType;
                vm.preData.customerTel=order.customerTel;
                vm.preData.contactPerson=order.contactPerson;
                vm.preData.customerType=order.customerType;
                vm.preData.lessorName=order.lessorName;
                vm.preData.timeStartRent=dateFormatYMD(order.orderCar.timeStartRent);
                vm.preData.timeFinishRent=dateFormatYMD(order.orderCar.timeFinishRent);
                vm.preData.vinNo=order.orderCar.vinNo;
                vm.preData.carBrandModel=order.orderCar.brandName+'/'+order.orderCar.seriesName+'/'+order.orderCar.modelName;
                vm.preData.deptName=order.orderCar.deptName
        },
        inputAlterationMileage:function(){
            this.applyForDTO.alterationMileage = checkNum(this.applyForDTO.alterationMileage);
        },
        // inputIllegalScore:function(){
        //     this.applyForDTO.illegalScore = checkNum(this.applyForDTO.illegalScore);
        // },
        inputHasPaid:function(){
            this.applyForDTO.hasPaid = checkNum(this.applyForDTO.hasPaid);
        },
        inputMargin:function(){
            this.applyForDTO.margin = checkNum(this.applyForDTO.margin);
        },
        // inputIllegalAmount:function(){
        //     this.applyForDTO.illegalAmount = checkNum(this.applyForDTO.illegalAmount);
        // },
        // inputDangerCount:function(){
        //     this.applyForDTO.dangerCount = checkNum(this.applyForDTO.dangerCount);
        // },
        // inputDangerAmount:function(){
        //     this.applyForDTO.dangerAmount = checkNum(this.applyForDTO.dangerAmount);
        // },
        // inputActualAmount:function(){
        //     this.applyForDTO.actualAmount = checkNum(this.applyForDTO.actualAmount);
        // },
        // inputDeductionAmount:function(){
        //     this.applyForDTO.deductionAmount = checkNum(this.applyForDTO.deductionAmount);
        // },
        inputRentAmount:function(){
            this.applyForDTO.rentAmount = checkNum(this.applyForDTO.rentAmount);
        },
        // inputDefaultAmount:function(){
        //     this.applyForDTO.defaultAmount = checkNum(this.applyForDTO.defaultAmount);
        // },
        // inputOtherAmount:function(){
        //     this.applyForDTO.otherAmount = checkNum(this.applyForDTO.otherAmount);
        // },
        // inputMaintenanceReduce:function(){
        //     this.applyForDTO.maintenanceReduce = checkNum(this.applyForDTO.maintenanceReduce);
        // },
        // inputWashCarReduce:function(){
        //     this.applyForDTO.washCarReduce = checkNum(this.applyForDTO.washCarReduce);
        // },
        // inputAddInsuranceFee:function(){
        //     this.applyForDTO.addInsuranceFee = checkNum(this.applyForDTO.addInsuranceFee);
        // },
        // inputCollectFee:function(){
        //     this.applyForDTO.collectFee = checkNum(this.applyForDTO.collectFee);
        // },
        // inputTransferCommission:function(){
        //     this.applyForDTO.transferCommission = checkNum(this.applyForDTO.transferCommission);
        // },
        // inputMargin:function(){
        //     this.applyForDTO.margin = checkNum(this.applyForDTO.margin);
        // },
        // inputotherFee:function(){
        //     this.applyForDTO.otherFee = checkNum(this.applyForDTO.otherFee);
        // },
        saveOrUpdate: function () {
            if(vm.settleType == 2){
                if(vm.applyForDTO.returnType == null || vm.applyForDTO.returnType == ''){
                    layer.msg('退车类型不能为空!', {icon: 7});
                    return false;
                }
            }
            if(vm.applyForDTO.rentType === 6){
                vm.applyForDTO.timeStartRent = null;
                vm.applyForDTO.timeFinishRent = null;
            }
            vm.applyForDTO.attachment = vm.deliveryFileLst;
            $.ajax({
                type: "POST",
                url: baseURL + "order/ordercaralteration/save2",
                contentType: "application/json",
                data: JSON.stringify(vm.applyForDTO),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            parent.layer.closeAll();
                            parent.vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        detail: function () {
            let data;
            var code = window.localStorage.getItem("code");
            var type = window.localStorage.getItem("type");
            vm.settleType = type;
            if (type == 1) { //换车
                vm.title = "申请换车";
                vm.dateLabel="换车时间";
                $("#marginDiv").hide();
                $("#typeDiv").hide();
            } else if (type == 2) { //退车
                vm.title = "申请退车";
                vm.dateLabel="退车时间";
                $("#marginDiv").show();
                $("#typeDiv").show();
            }
            setTimeout(() => {
                $.get(baseURL + "order/ordercaralteration/detailData/" + code, function (r) {
                    vm.applyForDTO = r.data;
                    vm.applyForDTO.alterationType = vm.settleType;
                    vm.applyForDTO.carNo = vm.preData.carNo;
                    vm.applyForDTO.code = vm.preData.code;
                    vm.applyForDTO.customerName = vm.preData.customerName;
                    vm.applyForDTO.rentTypeStr = vm.preData.rentTypeStr;
                    vm.applyForDTO.rentType = vm.preData.rentType;
                    vm.applyForDTO.customerTel = vm.preData.customerTel;
                    /*if(vm.preData.customerType === 1){
                        vm.applyForDTO.contactPerson = vm.preData.contactPerson;
                    }else{
                        vm.applyForDTO.contactPerson = vm.preData.customerName;
                    }*/
                    vm.applyForDTO.contactPerson = vm.preData.contactPerson;
                    vm.applyForDTO.lessorName = vm.preData.lessorName;
                    vm.applyForDTO.timeStartRent = vm.preData.timeStartRent;
                    vm.applyForDTO.timeFinishRent = vm.preData.timeFinishRent;
                    vm.applyForDTO.vinNo = vm.preData.vinNo;
                    vm.applyForDTO.carBrandModel = vm.preData.carBrandModel;
                    vm.applyForDTO.deptName = vm.preData.deptName;
                    if(r.data.rentType == 2 || r.data.rentType == 5 || r.data.rentType == 6){
                        $("#marginDiv").hide();
                    }
                    if(vm.settleType==1){
                        $.get(baseURL + "serviceConfig/getServiceConfig?suitType=2&suitRentType="+vm.applyForDTO.rentType, function (r) {
                            vm.backAmount=r.backAmount;
                            vm.illLegalAmount=r.illLegalAmount;
                            vm.insuranceAmount=r.insuranceAmount;
                            vm.decutionAmount=r.decutionAmount;
                            vm.bankInfo=r.bankInfo;
                            vm.notice=r.notice;
                        });
                    }else{
                        $.get(baseURL + "serviceConfig/getServiceConfig?suitType=1&suitRentType="+vm.applyForDTO.rentType, function (r) {
                            vm.backAmount=r.backAmount;
                            vm.illLegalAmount=r.illLegalAmount;
                            vm.insuranceAmount=r.insuranceAmount;
                            vm.decutionAmount=r.decutionAmount;
                            vm.bankInfo=r.bankInfo;
                            vm.notice=r.notice;
                        });

                    }
                    calculate2();
                  });
            }, 50);



        },
        cancel: function () {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },
        delDeliveryFile: function (id) {
            for (var i = 0; i < vm.deliveryFileLst.length; i++) {
                if (vm.deliveryFileLst[i].id === id) {
                    vm.deliveryFileLst.splice(i, 1);
                    i = i - 1;
                }
            }
        },
        chooseWarehouse:function(){
            var index = layer.open({
                title: "选择仓库",
                type: 2,
                area: ['80%', '80%'],
                content: tabBaseURL + "modules/warehouse/selectwarehouse.html",
                end: function(){
                    vm.applyForDTO = Object.assign({}, vm.applyForDTO,{
                        depotId:vm.warehouseData.warehouseId,
                        depotName:vm.warehouseData.warehouseName,
                    });
                    layer.close(index);
                }
            });
        },
        change:function (field){
            calculate2()
        },

        check:function (field,item){
           let fr=  checkNum(field);
           Vue.set(vm.applyForDTO, item, fr);
        },
        // illegalAmountChange: function () {
        //     calculate();
        // },
        marginChange: function () {
            calculate2();
        },
        hasPaidChange: function () {
            calculate2();
        },
        // marginChange: function () {
        //     calculate();
        // },
        // dangerAmountChange: function () {
        //     calculate();
        // },
        // actualAmountChange: function () {
        //     calculate();
        // },
        rentAmountChange: function () {
            calculate2();
        },
        // defaultAmountChange: function () {
        //     calculate();
        // },
        // otherAmountChange: function () {
        //     calculate();
        // },
        // deductionAmountChange:function () {
        //     calculate();
        // },
        // maintenanceReduceChange:function() {
        //     calculate();
        // },
        // washCarReduceChange:function() {
        //     calculate();
        // },
        // addInsuranceFeeChange:function() {
        //     calculate();
        // },
        // collectFeeChange:function() {
        //     calculate();
        // },
        // transferCommissionChange:function() {
        //     calculate();
        // },
        // transferotherFeeChange:function() {
        //     calculate();
        // },
        downDoc: function (fileName, url) {
            var uri = baseURL + 'file/download?uri='+url+"&fileName="+fileName;
            window.location.href = uri;
        },
        showDoc: function (fileName, url) {
            if (viewer != null){
                viewer.close();
                viewer = null;
            }
            viewer = new PhotoViewer([
                {
                    src: fileURL+url,
                    title: fileName
                }
            ], {
                appendTo:'body',
                zIndex:99891018
            });
        },
    }
});

/**
 * 计算结算金额
 */
function calculate() {
    vm.amount.dangerAmount = vm.applyForDTO.dangerAmount;
    vm.amount.deductionAmount = vm.applyForDTO.deductionAmount;
    vm.amount.margin = vm.applyForDTO.margin;
    vm.amount.hasPaid = vm.applyForDTO.hasPaid;
    vm.amount.deductionAmount = vm.applyForDTO.deductionAmount;
    vm.amount.illegalAmount = vm.applyForDTO.illegalAmount;
    vm.amount.actualAmount = vm.applyForDTO.actualAmount;
    vm.amount.rentAmount = vm.applyForDTO.rentAmount;
    vm.amount.defaultAmount = vm.applyForDTO.defaultAmount;
    vm.amount.otherAmount = vm.applyForDTO.otherAmount;
    vm.amount.type = vm.settleType;
    vm.amount.maintenanceReduce = vm.applyForDTO.maintenanceReduce;
    vm.amount.washCarReduce = vm.applyForDTO.washCarReduce;
    vm.amount.addInsuranceFee = vm.applyForDTO.addInsuranceFee;
    vm.amount.collectFee = vm.applyForDTO.collectFee;
    vm.amount.transferCommission = vm.applyForDTO.transferCommission;
    vm.amount.rentType = vm.applyForDTO.rentType;
    vm.amount.otherFee = vm.applyForDTO.otherFee;


    $.ajax({
        type: "POST",
        url: baseURL + "order/ordercaralteration/calculate",
        contentType: "application/json",
        data: JSON.stringify(vm.amount),
        success: function (r) {
            if (r.code === 0) {
                vm.settleAmount = r.data.amount;
                vm.applyForDTO.repayAmount = r.data.amount;
                vm.applyForDTO.repayType = r.data.type;
            } else {
                alert(r.msg);
            }
        }
    });
}
function calculate2() {
    $.ajax({
        type: "POST",
        url: baseURL + "order/ordercaralteration/calculateConfig",
        contentType: "application/json",
        data: JSON.stringify(vm.applyForDTO),
        success: function (r) {
            if (r.code === 0) {
                vm.settleAmount = r.data.amount;
                vm.applyForDTO.repayAmount = r.data.amount;
                vm.applyForDTO.repayType = r.data.type;
            } else {
                alert(r.msg);
            }
        }
    });


}


/**
 * 上传附件
 */
function uploadAttachment() {
    layui.upload.render({
        elem: '#addDeliveryFile',
        url: baseURL + 'file/uploadFile',
        data: {'path': 'order-delivery'},
        field: 'files',
        auto: true,
        size: 50 * 1024 * 1024,
        accept: 'file', //普通文件
        acceptMime: '.pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.jpeg,.zip,.rar,.mp4',
        exts: 'pdf|doc|docx|xls|xlsx|jpg|png|jpeg|zip|rar|mp4', //
        multiple: true,
        number:20,
        choose: function (obj) {
            PageLoading();
            obj.preview(function (index, file, result) {
                var fileName = file.name;
                var extIndex = fileName.lastIndexOf('.');
                var ext = fileName.slice(extIndex);
                var fileNameNotext = fileName.slice(0, extIndex);
                var regExt = /png|jpg|jpeg/;
                var fileType = regExt.test(ext) ? 1 : 0;
                deliveryFileIdTmp = vm.deliveryFileLst.length + '_' + uuid(60);
                var fileTmp = {
                    id: deliveryFileIdTmp,
                    nameDesc: '附件',
                    nameAccessory: fileNameNotext,
                    nameFile: fileName,
                    nameExt: ext,
                    typeFile: fileType,
                };
                vm.deliveryFileLst.push(fileTmp);
            });
        },
        done: function (res) {
            RemoveLoading();
            if (res.code == '0') {
                vm.deliveryFileLst.forEach(function (value) {
                    if (value.id === deliveryFileIdTmp) value.url = res.data[0];
                });
                vm.deliveryFileLstId = 'deliveryFileLstId_' + uuid(6);
            } else {
                layer.msg('上传失败', {icon: 5});
                vm.delDeliveryFile(deliveryFileIdTmp);
            }
            deliveryFileIdTmp = null;
        },
        error: function () {
            RemoveLoading();
            layer.msg('上传失败', {icon: 5});
            vm.delDeliveryFile(deliveryFileIdTmp);
            deliveryFileIdTmp = null;
        }
    });
}
